package com.ruoyi.system.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.SysExamine;
import com.ruoyi.system.mapper.SysExamineMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class HttpsUtlis {

    private static SysExamineMapper sysExamineMapper;

    @Autowired
    public void setUniDepartOrderMapper(SysExamineMapper sysExamineMapper) {
        HttpsUtlis.sysExamineMapper = sysExamineMapper;
    }


    /**
     * 获取节点
     * @return
     */
    public String nodeId(){
        // 获取查询检测配置数据
        SysExamine sysExamine = sysExamineMapper.selectOne((new LambdaQueryWrapper<SysExamine>().eq(SysExamine::getDeleted, 0)));
        // 判断是否为空
        if(Objects.isNull(sysExamine)){
            throw new ServiceException("未获取到检测配置数据");
        }
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("key", sysExamine.getSecretKet());
        // 发起 GET 请求
        String result3 = HttpUtil.get("https://api.boce.com/v3/node/list", params);
        // 解析返回的 JSON 数据
        JSONObject parse = JSON.parseObject(result3);
        if(!parse.get("error_code").toString().equals("0")){
            throw new ServiceException(parse.get("error").toString());
        }
        // 获取 "data" 字段，它是一个包含 "list" 字段的对象
        JSONObject data = parse.getJSONObject("data");
        // 获取 "list" 字段，它是一个 JSONArray
        JSONArray list = data.getJSONArray("list");
        // 使用 StringBuilder 来拼接 id
        StringBuilder ids = new StringBuilder();
        // 遍历 list 数组，提取每个对象的 id
        for (int i = 0; i < list.size(); i++) {
            JSONObject node = list.getJSONObject(i);
            Object id = node.get("id");
            if (i > 0) {
                ids.append(",");
            }
            ids.append(id.toString());
        }
        return ids.toString();
    }


    /**
     * 添加任务
     * @return
     */
    public int create(String url){
        // 获取查询检测配置数据
        SysExamine sysExamine = sysExamineMapper.selectOne((new LambdaQueryWrapper<SysExamine>().eq(SysExamine::getDeleted, 0)));
        // 判断是否为空
        if(Objects.isNull(sysExamine)){
            throw new ServiceException("未获取到检测配置数据");
        }
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("key",sysExamine.getSecretKet());
        params.put("node_ids", nodeId());
        params.put("host",url);
        String data = HttpUtil.get("https://api.boce.com/v3/task/create/curl", params);
        //解析出返回数据
        Map parse = (Map) JSON.parse(data);
        //判断是否添加成功
        if(!parse.get("error_code").toString().equals("0")){
            throw new ServiceException(parse.get("error").toString());
        }
        Map data_id = (Map) JSON.parse(parse.get("data").toString());
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            // 处理中断异常
            e.printStackTrace();
        }
        return taskResult(data_id.get("id").toString());
    }

    /**
     * 获取任务结果
     */
    public int taskResult(String id){
        // 获取查询检测配置数据
        SysExamine sysExamine = sysExamineMapper.selectOne((new LambdaQueryWrapper<SysExamine>().eq(SysExamine::getDeleted, 0)));
        // 判断是否为空
        if(Objects.isNull(sysExamine)){
            throw new ServiceException("未获取到检测配置数据");
        }
        // 请求添加任务
        String data = HttpUtil.get("https://api.boce.com/v3/task/curl/" + id + "?key=" + sysExamine.getSecretKet());
        // 解析出返回数据
        Map parse = (Map) JSON.parse(data);
        //判断是否有值
        if(Objects.nonNull(parse.get("list"))){
            // 获取 list 字段
            List<Map<String, Object>> list = (List<Map<String, Object>>) parse.get("list");
            // 累加统计 http_code 不等于 200 的数量
            int errorCount = 0;
            // 遍历 list，检查 http_code
            for (Map<String, Object> item : list) {
                Object httpCodeObj = item.get("http_code");
                if (httpCodeObj != null && !httpCodeObj.toString().equals("200")) {
                    // 这里累加统计 http_code 不为 200 的数量
                    errorCount++;
                }
            }
            return errorCount;
        }
        return 0;
    }


}
